
export default class myCanvas {
    constructor(canvasId, instance) {
        this.canvasId = canvasId
        if (!instance) {
            this.querySelect = uni.createSelectorQuery()
        } else {
            this.querySelect = uni.createSelectorQuery().in(instance)
        }
        this.init()
    }
    init() {
        this.querySelect.select(`#${this.canvasId}`).fields({
            node: true,
            size: true
        }).exec((res) => {
            this.canvas = res[0].node
            this.ctx = this.canvas.getContext('2d')
            this.dpr = uni.getWindowInfo().pixelRatio

            const renderWidth = res[0].width
            const renderHeight = res[0].height

            this.canvas.width = renderWidth * this.dpr
            this.canvas.height = renderHeight * this.dpr
            this.ctx.scale(this.dpr, this.dpr)
        })
    }

    // 绘制图片
    drawImage(img, x, y, width, height, beforeDraw, afterDraw) {
        const image = this.canvas.createImage()
        image.src = img
        image.onload = async () => {
            if (beforeDraw) {
                await beforeDraw()
            }
            this.ctx.drawImage(image, x, y, width, height)
            if (afterDraw) {
                afterDraw()
            }
        }
    }
    // 清除画布
    clearRect(x, y, width, height) {
        this.ctx.clearRect(x, y, width, height)
    }

    // 画笔涂抹
    drawBrush(x, y, dx, dy, size = 10, color = '#FFF') {
        this.ctx.beginPath()
        this.ctx.moveTo(x, y)
        this.ctx.lineCap = "round"
        this.ctx.lineTo(dx, dy)
        this.ctx.strokeStyle = color; // 画笔 or 橡皮擦
        this.ctx.lineWidth = size; // 画笔宽度
        this.ctx.stroke();
        this.ctx.closePath();
    }
    // 让擦除更平滑的方法（插值补点）---（上个x,y,当前x,y）
    smoothErase(x1, y1, x2, y2, size) {
        const dx = x2 - x1;
        const dy = y2 - y1;
        const distance = Math.sqrt(dx * dx + dy * dy);
        const steps = Math.ceil(distance / (size / 6));  // 增加插值步数以减少裂齿状

        for (let i = 0; i <= steps; i++) {
            const interpolatedX = x1 + (dx * i) / steps;
            const interpolatedY = y1 + (dy * i) / steps;
            this.erase(interpolatedX, interpolatedY, size);
        }
    }

    // 橡皮擦擦除
    erase(dx, dy, size) {
        this.ctx.globalCompositeOperation = "destination-out"; // 关键：橡皮擦模式
        this.ctx.fillStyle = 'rgba(0, 0, 0, 1)' // 必须不透明
        this.ctx.beginPath();
        this.ctx.arc(dx, dy, size / 2, 0, Math.PI * 2, true);
        this.ctx.fill();
        this.ctx.closePath();
        this.ctx.globalCompositeOperation = "source-over"; // 取消橡皮擦模式
    }
    // 绘制圆形
    drawRoundedRect(dx, dy, size, radius, color = '#FFF') {
        const x = dx - size / 2;
        const y = dy - size / 2;
        const width = size;
        const height = size;

        this.ctx.beginPath();
        this.ctx.moveTo(x + radius, y);
        this.ctx.lineTo(x + width - radius, y);
        this.ctx.arcTo(x + width, y, x + width, y + radius, radius);
        this.ctx.lineTo(x + width, y + height - radius);
        this.ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius);
        this.ctx.lineTo(x + radius, y + height);
        this.ctx.arcTo(x, y + height, x, y + height - radius, radius);
        this.ctx.lineTo(x, y + radius);
        this.ctx.arcTo(x, y, x + radius, y, radius);
        this.ctx.closePath();
        this.ctx.fillStyle = color;
        this.ctx.fill();
    }
    // 绘制圆角矩形
    drawRoundedRectangle(x, y, width, height, radius, color = '#FFF') {
        this.ctx.beginPath();
        this.ctx.moveTo(x + radius, y);
        this.ctx.lineTo(x + width - radius, y);
        this.ctx.arcTo(x + width, y, x + width, y + radius, radius);
        this.ctx.lineTo(x + width, y + height - radius);
        this.ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius);
        this.ctx.lineTo(x + radius, y + height);
        this.ctx.arcTo(x, y + height, x, y + height - radius, radius);
        this.ctx.lineTo(x, y + radius);
        this.ctx.arcTo(x, y, x + radius, y, radius);
        this.ctx.closePath();
        this.ctx.fillStyle = color;
        this.ctx.fill();
    }

    // 绘制矩形
    drawRect(x, y, width, height, color = '#FFF') {
        this.ctx.beginPath();
        this.ctx.rect(x, y, width, height);
        this.ctx.fillStyle = color;
        this.ctx.fill();
        this.ctx.closePath();
    }

    // 绘制带边框的矩形，支持背景颜色或背景图
    drawBorderedRect(x, y, width, height, options = {}) {
        return new Promise(resolve => {
            const {
                borderColor = '#000',
                borderWidth = 2,
                backgroundColor = null,
                backgroundImage = null,
                drawImgBefore = null,
                drawImgAfter = null
            } = options;

            // 绘制边框
            this.ctx.beginPath();
            this.ctx.rect(x + borderWidth / 2, y + borderWidth / 2, width - borderWidth, height - borderWidth);
            this.ctx.lineWidth = borderWidth;
            this.ctx.strokeStyle = borderColor;
            this.ctx.stroke();
            this.ctx.closePath();

            // 绘制背景颜色
            if (backgroundColor) {
                this.ctx.beginPath();
                this.ctx.rect(x + borderWidth / 2, y + borderWidth / 2, width - borderWidth, height - borderWidth);
                this.ctx.fillStyle = backgroundColor;
                this.ctx.fill();
                this.ctx.closePath();
            }

            // 绘制背景图
            if (backgroundImage) {
                const image = this.canvas.createImage();
                image.src = backgroundImage;
                image.onload = () => {
                    if (drawImgBefore) {
                        drawImgBefore()
                    }
                    this.ctx.drawImage(
                        image,
                        x + borderWidth / 2,
                        y + borderWidth / 2,
                        width - borderWidth,
                        height - borderWidth
                    );
                    if (drawImgAfter) {
                        drawImgAfter()
                    }
                    resolve()
                };
            }

        })
    }
    // 检测涂抹画布是否有涂抹过
    hasDrawn(x, y, width, height) {
        const imageData = this.ctx.getImageData(x, y, width, height);
        const data = imageData.data;
        for (let i = 0; i < data.length; i += 4) {
            const [r, g, b, a] = [data[i], data[i + 1], data[i + 2], data[i + 3]];
            if (r !== 0 || g !== 0 || b !== 0 || a !== 0) { // 检查 RGB 或 alpha 通道是否发生变化
                return true;
            }
        }
        return false;
    }
    // 绘制文字
    drawText(text, x, y, options = {}) {
        const {
            color = '#000',
            fontSize = 16, // 新增 fontSize 参数
            font = `${fontSize}px sans-serif`, // 使用 fontSize 设置字体大小
            textAlign = 'left',
            textBaseline = 'alphabetic',
            maxWidth = null
        } = options;

        this.ctx.font = font;
        this.ctx.fillStyle = color;
        this.ctx.textAlign = textAlign;
        this.ctx.textBaseline = textBaseline;

        if (maxWidth) {
            this.ctx.fillText(text, x, y, maxWidth);
        } else {
            this.ctx.fillText(text, x, y);
        }
    }

    // 绘制四周可以拖动的边框矩形
    drawDraggableBorderedRect(x, y, width, height, options = {}) {
        const {
            borderColor = '#FFF',
            borderWidth = 2,
            backgroundColor = null // 新增背景颜色选项
        } = options;

        // 绘制边框
        // this.ctx.beginPath();
        // this.ctx.rect(x + borderWidth / 2, y + borderWidth / 2, width - borderWidth, height - borderWidth);
        // this.ctx.lineWidth = borderWidth;
        // this.ctx.strokeStyle = borderColor;
        // this.ctx.stroke();
        // this.ctx.closePath();

        // 绘制背景颜色
        if (backgroundColor) {
            this.ctx.beginPath();
            this.ctx.rect(x + borderWidth / 2, y + borderWidth / 2, width - borderWidth, height - borderWidth);
            this.ctx.fillStyle = backgroundColor;
            this.ctx.fill();
            this.ctx.closePath();
        }

        const dragBorderWidth = 20; // 拖动边框的宽度
        const dragBorderHeight = 5; // 拖动边框的高度

        // 绘制边框
        this.drawRoundedRectangle(x, y, dragBorderWidth, dragBorderHeight, 2, borderColor); // 上左边框
        this.drawRoundedRectangle(x + width - dragBorderWidth, y, dragBorderWidth, dragBorderHeight, 2, borderColor); // 上右边框

        this.drawRoundedRectangle(x, y, dragBorderHeight, dragBorderWidth, 2, borderColor); // 左上边框
        this.drawRoundedRectangle(x + width - dragBorderHeight, y, dragBorderHeight, dragBorderWidth, 2, borderColor); // 右上边框

        this.drawRoundedRectangle(x, y + height - dragBorderWidth, dragBorderHeight, dragBorderWidth, 2, borderColor); // 左下边框
        this.drawRoundedRectangle(x, y + height - dragBorderHeight, dragBorderWidth, dragBorderHeight, 2, borderColor); // 下左边框

        this.drawRoundedRectangle(x + width - dragBorderWidth, y + height - dragBorderHeight, dragBorderWidth, dragBorderHeight, 2, borderColor); // 下右边框
        this.drawRoundedRectangle(x + width - dragBorderHeight, y + height - dragBorderWidth, dragBorderHeight, dragBorderWidth, 2, borderColor); // 右下边框
    }

}


// 检查图片是否透明并根据图片信息绘制
// 通过检查图片的透明度来判断图片是否包含透明像素
export function checkImageTransparency(filePath) {
    return new Promise(async (resolve, reject) => {
        try {
            const { width, height } = await uni.getImageInfo({ src: filePath });

            // 创建离屏 Canvas
            const canvas = wx.createOffscreenCanvas({ type: "2d", width, height });
            const ctx = canvas.getContext("2d");
            const img = canvas.createImage();

            img.onload = () => {
                ctx.drawImage(img, 0, 0, width, height);

                // 检查四个角的透明度
                const corners = [
                    { x: 0, y: 0 }, // 左上角
                    { x: width - 1, y: 0 }, // 右上角
                    { x: 0, y: height - 1 }, // 左下角
                    { x: width - 1, y: height - 1 }, // 右下角
                ];

                const isTransparent = corners.some(({ x, y }) => ctx.getImageData(x, y, 1, 1).data[3] === 0);

                isTransparent ? resolve() : reject(new Error("图片不包含透明背景。"));
            };

            img.onerror = () => reject(new Error("加载图片失败。"));
            img.src = filePath; // 设置图片路径
        } catch {
            reject(new Error("获取图片信息失败。"));
        }
    });
}
